const path = require('path')
const { createUser, getUserInfo } = require('@/service/user')
const jwt = require('jsonwebtoken')
const { JWT_SECRET } = require('@/config/config.default')
const { uploadFileError } = require('@/constant/errType')
const result = require('@/constant/result')

class UserController {
  async register(ctx, next) {
    const {username, password} = ctx.request.body
    try {
      const res = await createUser(username, password)
      ctx.body = {
        code: 200,
        message: '用户注册成功',
        data: {
          username: res.username
        }
      }
      return ctx
    }catch(err){
      console.error('用户注册失败', err)
    }
  }
  async login(ctx, next) {
    const { username } = ctx.request.body
    try {
      const {...res} = await getUserInfo({username})
      const {password, _id, ...obj} = res._doc
      ctx.body =  result.success('用户登录成功', {
        user: obj,
        token: jwt.sign(obj, JWT_SECRET, {expiresIn: '1d'})
      })
      return ctx
    } catch(err){
      console.error('用户登录失败----', err)
    }
  }
  async info(ctx, next) {
    try {
      ctx.body = {
        ok: true,
        msg: '获取信息成功',
        data: [{list:1},{list:2}]
      }
      return ctx
    } catch(err) {
      console.error('获取用户信息失败', err)
    }
  }
  async upload(ctx, next) {
    const { file } = ctx.request.files
    // 类型判断
    const fileType = ['image/jpeg', 'image/png']
    if (file) {
      if (!fileType.includes(file.mimetype)){
        return ctx.app.emit('error', uploadFileError, ctx)
      }
      ctx.body = {
        code: '10010',
        message: '上传成功',
        data: {
          img: path.basename(file.filepath)
        }
      }
      return ctx
    } else {
      return ctx.app.emit('error', uploadFileError, ctx)
    }
  }
}

module.exports = new UserController()